<?php
namespace Com\Weixin;

/**
 * 微信基础接口
 *
 * @author codebean
 *        
 */
class WeixinApi
{

    private $appId = null;

    private $appSecret = null;

    public function __construct($appId = null, $appSecret = NULL)
    {
        $this->appId = $appId ? $appId : C('AppID');
        $this->appSecret = $appSecret ? $appSecret : C('AppSecret');
    }

    /**
     * 文本消息
     *
     * @param unknown $openid            
     * @param unknown $content            
     * @return string
     */
    public function sendText($openid, $content)
    {
        $access_token = $this->getToken();
        
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        
        $data = array();
        $data['touser'] = $openid;
        $data['msgtype'] = "text";
        $data['text']['content'] = $content;
        $data = JSON($data);
        $rs = https_request($url, $data);
        $ret = json_encode($rs, true);
        if ($ret['errcode'] != 0)
        {
            my_log('sendText fail:' . implode(',', $ret));
        }
        
        return $ret;
    }

    /**
     * 图片消息
     *
     * @param unknown $openid            
     * @param unknown $media_id            
     */
    public function sendPicture($openid, $media_id)
    {
        $access_token = $this->getToken();
        
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        
        $data = array();
        $data['touser'] = $openid;
        $data['msgtype'] = "image";
        $data['image']['media_id'] = $media_id;
        $data = JSON($data);
        $rs = https_request($url, $data);
        $ret = json_encode($rs, true);
        if ($ret['errcode'] != 0)
        {
            my_log('sendText fail:' . implode(',', $ret));
        }
        
        return $ret;
    }

    /**
     * 获取推广二维码图片
     *
     * @param unknown $path_name            
     * @param unknown $code            
     * @param string $code_is_str            
     * @return unknown|boolean
     */
    public function getQr($path_name, $code, $code_is_str = false)
    {
        $access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" . $access_token;
        
        $data = array();
        
        if ($code_is_str)
        {
            $data['action_name'] = 'QR_LIMIT_STR_SCENE';
            $data['action_info']['scene']['scene_str'] = $code;
        } else
        {
            $data['action_name'] = 'QR_LIMIT_SCENE';
            $data['action_info']['scene']['scene_id'] = $code;
        }
        $data = JSON($data);
        $rs = https_request($url, $data);
        $rs1 = json_decode($rs, true);
        
        if ($rs1 && $rs1['ticket'])
        {
            $ticket = $rs1['ticket'];
            $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);
            
            $http = new \Org\Net\Http();
            
            $http->curlDownload($url, $path_name);
            
            return $path_name;
        } else
        {
            my_log("get qr fail: " . $rs);
        }
        
        return false;
    }

    /**
     * 获取access token
     *
     * @param string $is_force            
     * @return unknown|unknown|mixed|object|boolean
     */
    public function getToken($is_force = false)
    {
        if ($is_force == false)
        {
            $data = S("access_token");
            if ($data)
            {
                if (is_array($data) && $data['expire_time'] > time())
                {
                    $access_token = $data['access_token'];
                    return $access_token;
                } else if (is_string($data))
                {
                    $access_token = $data;
                    return $access_token;
                }
            }
            
            // 非强制获取access_token，cache没有就直接返回false，防止获取access_token的接口在高并发下被滥用
            return false;
        }
        
        $appId = $this->appId;
        $appSecret = $this->appSecret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appId . '&secret=' . $appSecret;
        $rs1 = https_request($url);
        
        if ($rs1)
        {
            $rs = json_decode($rs1, true);
            if (is_array($rs) && $rs['access_token'])
            {
                $access_token = $rs['access_token'];
                $expires_in = intval($rs['expires_in'], 10);
                if ($expires_in <= 0)
                {
                    $expires_in = 5;
                } else if ($expires_in >= 7200)
                {
                    $expires_in = 7000;
                }
                
                $data = array();
                $data['expire_time'] = time() + $expires_in;
                $data['access_token'] = $access_token;
                
                S('access_token', $data, $expires_in);
                return $access_token;
            } else
            {
                $content = "get access token error:" . $rs1;
                my_log($content);
            }
        } else
        {
            $content = "get access token error:" . $rs1;
            my_log($content);
        }
        
        return false;
    }

    /**
     * 上传图文消息素材
     */
    public function uploadnews($news_pic)
    {
        $access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=" . $access_token;
        
        $data = array();
        
        $data['articles'] = $news_pic;
        
        $data = JSON($data);
        $rs = https_request($url, $data);
        $ret = json_decode($rs, true);
        
        if (isset($ret['errcode']))
        {
            my_log('uploadnews fail:' . implode(',', $ret));
            return false;
        }
        
        return $ret;
    }

    public function previewMessage($openid, $media_id, $type = "mpnews")
    {
        $access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" . $access_token;
        
        $data = array();
        $data['touser'] = $openid;
        
        $data[$type]['media_id'] = $media_id;
        $data['msgtype'] = $type;
        
        $data = JSON($data);
        
        var_dump($data);
        
        $rs = https_request($url, $data);
        $ret = json_decode($rs, true);
        
        if (isset($ret['errcode']))
        {
            my_log('previewMessage fail:' . implode(',', $ret));
            return false;
        }
        
        return $ret;
    }
    
    
    /**
     * 模板消息
     *
     * @param unknown $openid
     * @param unknown $content
     * @return string
     */
    public function sendTemplateMsg($openid ,$content , $tmp_id , $url)
    {
        $access_token = $this->getToken();
    
        $url1 = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
    
        $data = array();
        $data['touser'] = $openid;
        $data['template_id'] = $tmp_id;
    
        if( $url ){
            $data['url'] = $url;
        }
    
        $data['data'] = $content;
    
        $data = JSON($data);
        $rs = https_request($url1, $data);
        $ret = json_encode($rs, true);
        if ($ret['errcode'] != 0)
        {
            my_log('sendText fail:' . implode(',', $ret));
        }
    
        return $ret;
    }
}